package ufc.si.auditoria.tcp;

import java.net.*;
import java.io.*;

import ufc.si.auditoria.util.AESUtil;

public class TCPClient {

	Socket s;
	DataInputStream in; 
	DataOutputStream out;
	
	public TCPClient(String ip){
		Connection(ip);
	}
	
	public String getResponse(){
		
		try {
			int tamanho = in.readInt();
			byte[] fromClient = new byte[tamanho];
            in.read(fromClient, 0, tamanho);
			System.out.println("Recebido criptografado: "+new String(fromClient));
			String data = AESUtil.decriptografar(fromClient);
			System.out.println("Recebido decriptografado: "+data);
			return data;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	public void sendRequest(String request) {
		try {
			System.out.println("Enviado decriptografado: "+request);
			byte[] cifrado = AESUtil.encriptografar(request);
			System.out.println("Enviado criptografado: "+new String(cifrado));
			out.writeInt(cifrado.length);
			out.write(cifrado);
		} catch (UnknownHostException e) {
			System.out.println("Socket:" + e.getMessage());
		} catch (EOFException e) {
			System.out.println("EOF:" + e.getMessage());
		} catch (IOException e) {
			System.out.println("readline:" + e.getMessage());
		} catch (Exception e){
			System.out.println("criptografia:"+e.getMessage());
		}
	}

	public void close() {
		if (s != null){
			try {
				s.close();
			} catch (IOException e) {
				System.out.println("close:" + e.getMessage());
			}
		}	
	}
	
	private void Connection(String ip){
		int serverPort = 7896;
		try {
			s = new Socket(ip, serverPort);
			in = new DataInputStream(s.getInputStream());
			out = new DataOutputStream(s.getOutputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}